package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.vo.PageResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.common.pojo.Comment;
import com.tanhua.common.pojo.Comments;
import com.tanhua.common.vo.PageInfo;
import com.tanhua.server.utils.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 景银泰
 * date 2020-11-18 10:59
 * Description :
 * Version :
 */
@Service
public class CommentsService {
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询评论
     *
     * @param publishId
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult queryCommentsList(String publishId, Integer page, Integer pagesize) {
        User user = null;
        try {
            user = UserThreadLocal.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //从mogodb中获取publishId 动态  评论所有信息
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentList(publishId, page, pagesize);
        PageResult pageResult = new PageResult();
        if (pageInfo == null) {
            pageResult.setPage(page);
            pageResult.setPagesize(pagesize);
            return pageResult;
        }
        List<Comment> records = pageInfo.getRecords();
        List<Long> useIds = new ArrayList<>();
        List<Comments> commentsList = new ArrayList<>();

        //从records中获取评论人id   从而获取头像等信息
        for (Comment record : records) {
            if (!useIds.contains(record.getId())) {
                useIds.add(record.getUserId());
            }

        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("user_id", useIds);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);

        for (Comment record : records) {
            for (UserInfo userInfo : userInfos) {
                if (record.getUserId() == userInfo.getUserId()) {
                    Comments comments = new Comments();
                    comments.setId(record.getUserId());
                    comments.setContent(record.getContent());
                    comments.setCreateDate(new DateTime(record.getCreated()).toString("yyyy年MM月dd日 HH:mm"));
                    comments.setAvatar(userInfo.getLogo());
                    comments.setNickname(userInfo.getNickName());

                    String key = "QUANZI_COMMENTS_LIKE_" + comments.getId();
                    String value = this.redisTemplate.opsForValue().get(key);
                    if (StringUtils.isNotEmpty(value)) {
                        comments.setLikeCount(Integer.valueOf(value)); //点赞数
                    } else {
                        comments.setLikeCount(0);
                    }
                    String userKey = "QUANZI_COMMENTS_LIKE_USER_" + user.getId() + "_" + comments.getId();
                    comments.setHasLiked(this.redisTemplate.hasKey(userKey) ? 1 : 0); //是否点赞（1是，0否）

                    commentsList.add(comments);
                }


            }

        }
        pageResult.setItems(commentsList);
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setPages(0);
        pageResult.setCounts(0);

        return pageResult;


    }

    /**
     * 评论动态
     *
     * @param publishId
     * @param content
     * @return
     */
    public Boolean saveComments(String publishId, String content) {
        User user = UserThreadLocal.get();
        return this.quanZiApi.saveComment(user.getId(), publishId, 2, content);


    }

    /**
     * 给评论点赞
     *
     * @param publishId
     * @return
     */
    public Boolean likeComments(String publishId) {
        User user = UserThreadLocal.get();
        String key = "QUANZI_COMMENTS_LIKE_" + publishId;
        String userKey = "QUANZI_COMMENTS_LIKE_USER_" + user.getId() + "_" + publishId;
        if (this.redisTemplate.hasKey(userKey)) {
            return false;
        }
        this.redisTemplate.opsForValue().set(userKey, "1");

        this.redisTemplate.opsForValue().increment(key);
        return true;

    }

    /**
     * 给评论取消点赞
     *
     * @param publishId
     * @return
     */
    public Boolean dislikeComments(String publishId) {
        User user = UserThreadLocal.get();
        String key = "QUANZI_COMMENTS_LIKE_" + publishId;  //TODO   QUANZI_COMMENTS_LIKE_    评论点赞存入数据库key
        String userKey = "QUANZI_COMMENTS_LIKE_USER_" + user.getId() + "_" + publishId;
        if (this.redisTemplate.hasKey(userKey)) {
            this.redisTemplate.delete(userKey);
            this.redisTemplate.opsForValue().decrement(key);
            return true;
        }
        return false;

    }
}
